package com.wendy.authentication;

import com.wendy.mapper.AuthorityMapper;
import com.wendy.mapper.RoleMapper;
import com.wendy.model.Authority;
import com.wendy.model.Role;
import com.wendy.model.User;
import com.wendy.service.UserService;
import com.wendy.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhuwending
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthorityMapper authorityMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectUserByUsername(username);
        if (null != user) {
            return getUserDetails(user);
        } else {
            throw new UsernameNotFoundException(username + "do not exists");
        }
    }

    private UserDetails getUserDetails(User user) {
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Long userId = user.getId();
        List<Role> roles = roleMapper.selectRoleByUserId(userId);
        Set<String> authors = new HashSet<>();
        if (roles != null && roles.size() > 0) {
            roles.forEach(role -> authors.add(role.getCode()));
        }
        List<Authority> authorities = authorityMapper.selectAuthorityByUserId(userId);
        if (authorities != null && authorities.size() > 0) {
            authorities.forEach(authority -> authors.add(authority.getPermissions()));
        }
        Collection<? extends GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(authors.toArray(new String[0]));
        return new UserDetail(userId, user.getUsername(), user.getPassword(), StringUtils.equals(user.getStatus(), Constants.STATUS_NORMAL),
                true, true, true, grantedAuthorities);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        User user = new User();
        user.setUsername(userId);

        return null;
    }
}
